package com.itheima.stock.sharding;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

import java.text.DateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author: siwukun
 * @date: 2022/06/13
 * @description:
 */
public class CommonShardingAlgorithm4Db implements PreciseShardingAlgorithm<Date>, RangeShardingAlgorithm<Date> {

    /**
     * 精准策略
     * @param dbNames
     * @param preciseShardingValue
     * @return
     */


    @Override
    public String doSharding(Collection<String> dbNames, PreciseShardingValue<Date> preciseShardingValue) {

        //获取分片值
        Date date = preciseShardingValue.getValue();
        //获取年份
        String year = new DateTime(date).getYear()+"";
        //从dbNames集合中查找以year结尾的数据
        final Optional<String> first = dbNames.stream().filter(dbName -> dbName.endsWith(year)).findFirst();
        String dbActul= "";
        //数据源是否存在
        if (first.isPresent()){
            dbActul=first.get();
        }
        return dbActul;
    }


    /**
     *  范围策略
     * @param dbNames
     * @param rangeShardingValue
     * @return
     */
    @Override
    public Collection<String> doSharding(Collection<String> dbNames, RangeShardingValue<Date> rangeShardingValue) {
        //获取分片值
        final Range<Date> valueRange = rangeShardingValue.getValueRange();
        //判断是否有下限值
        if (valueRange.hasLowerBound()) {
            Date lowerDate = valueRange.lowerEndpoint();
            //获取年份  dsNames--> ds_2021 ds_2022 ds_2023
            int year = new DateTime(lowerDate).getYear();//2022
            dbNames = dbNames.stream().filter(dsName -> Integer.valueOf(dsName.substring(dsName.lastIndexOf("-") + 1)) >= year)
                    .collect(Collectors.toList());
        }
        //2.2 判断是否有上限值
        if (valueRange.hasUpperBound()) {
            Date upperDate = valueRange.upperEndpoint();
            int year = new DateTime(upperDate).getYear();
            dbNames= dbNames.stream().filter(dsName->Integer.valueOf(dsName.substring(dsName.lastIndexOf("-")+1))<=year)
                    .collect(Collectors.toList());
        }
        return dbNames;
    }
}
